<template>
    <a-card :bordered="false">
        <a-modal :visible="visibleUpload" @cancel="() => { this.visibleUpload = false; }">
            <a-upload name="file" :multiple="false" :showUploadList="false" :action="$rootUrl + leading" :headers="headers"
                @change="handleChange" style="display: inline-block" accept=".xlsx,.xls" class="upload-list-inline"
                >
                <a-button type="primary">
                    <a-icon type="upload" />
                    上传Excel数据
                </a-button>
            </a-upload>
            <template slot="footer">
                <a-button @click="() => { this.visibleUpload = false; }">关闭</a-button>
            </template>
        </a-modal>
        <a-modal :confirmLoading="loading" :visible="visible" title="订单于返料规则" width="30%" @cancel="() => {
            this.visible = false
        }
            ">
            <template slot="footer">
                <a-button key="back" @click="visible = false">
                    关闭
                </a-button>
            </template>
            <div class="flax">
                <div class="download">
                    <a-button style="margin-left: 8px" @click="openhtml()">
                        <a-icon type="download" />
                        导出订单返料规则
                    </a-button>
                </div>
                <a-upload :action="$rootUrl + '/OrderManagement/SO_SOMain/ImportForUpdateSO_SOMainAndRule'"
                    :headers="headers" :multiple="true" name="file" @change="handleChange">
                    <a-button style="margin-left: 8px">
                        <a-icon type="upload" />
                        导入订单返料规则
                    </a-button>
                </a-upload>
            </div>
        </a-modal>
        <div class="table-operator">
            <a-button v-if="hasPerm('SO_SOMain.Add')" icon="plus" type="primary" @click="handleAdd()">新建</a-button>
            <a-button v-if="hasPerm('SO_SOMain.Delete')" :disabled="!hasSelected()" :loading="loading" icon="minus"
                type="primary" @click="handleDelete(selectedRowKeys)">删除
            </a-button>
            <!-- <a-button icon="redo" type="primary" @click="getDataList()">刷新</a-button> -->
            <!-- <a-button type="primary" icon="upload" @click="handleImport()">导入</a-button> -->
            <a-button v-if="hasPerm('Cust_CustomerLinkMan.Import')" style="margin-left: 8px" type="primary" @click="() => {
                this.visible = true
            }
                ">返料规则绑定
            </a-button>
        </div>

        <div class="table-page-search-wrapper">
            <a-form layout="inline">
                <a-row :gutter="10">
                    <a-col :md="4" :sm="24">
                        <a-form-item label="查询类别">
                            <a-select v-model="queryParam.condition" allowClear>
                                <a-select-option key="salesman">业务员名称</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md="4" :sm="24">
                        <a-form-item>
                            <a-input v-model="queryParam.keyword" placeholder="关键字" @keydown.enter="getDataList" />
                        </a-form-item>
                    </a-col>
                    <a-col :md="14" :sm="24">
                        <a-select style="width: 100px;margin-left: 8px;" v-model="selectTime" @change="changeTime" name="radioGroup" :default-value="0">
                  <a-select-option :value="index" v-for="(i, index) in ['一个月', '三个月', '六个月', '自定义']" :key="i">
                    {{ i }}
                  </a-select-option>
                </a-select>
                        <a-range-picker style="margin-left: 8px;width: 220px;" :disabled="timeDisabled" v-model="time" />
                        <a-button style="margin-left: 10px;" type="primary" @click="() => {
                            this.pagination.current = 1
                            this.getDataList()
                        }
                            ">查询
                        </a-button>
                        <a-button style="margin-left: 8px;margin-right: 8px;" @click="repossess">重置</a-button>
                        <a-button type="primary" icon="download" @click="downloadTemplate">导出</a-button>
                    </a-col>
                </a-row>
            </a-form>
        </div>

        <a-table ref="table" :bordered="true" :columns="columns" :dataSource="data" :loading="loading"
            :pagination="pagination" :rowKey="(row, index) => row.ID" :scroll="{ y: 530 }" size="small"
            @change="handleTableChange">
            <!-- <span slot="CreateTime" slot-scope="CreateTime">{{ timeFormat(CreateTime) }}</span> -->
            <span slot="action" slot-scope="text, record">
                <template>
                    <a @click="handleEdit(record)">查看</a>
                    <a-divider v-if="hasPerm('SO_SOMain.Edit') && hasPerm('SO_SOMain.Delete')" type="vertical" />
                    <a v-if="hasPerm('SO_SOMain.Delete')" @click="handleDelete([record.Id])">删除</a>
                </template>
            </span>
        </a-table>

    </a-card>
</template>

<script>
import Token from '@/utils/cache/TokenCache'
import moment from 'moment'
import { download } from '@/components/download'

const columns = [

    // {
    //     title: '单据日期',
    //     dataIndex: 'time',
    //     align: 'center',
    //     customRender: (value, row) => {
    //         return row.CreateTime.substring(0, 10)
    //     },
    // },
    { title: '业务员姓名', dataIndex: 'salesman' },

    // { title: '业务员id', dataIndex: 'cCusName', width: '25%' },
    { title: '开票数量', dataIndex: 'InvoiceQuantity', align: 'right' },
    { title: '销售金额', dataIndex: 'InventoryAmount', align: 'right', },
    // { title: '销售类型', dataIndex: 'cSTCode' },
    { title: '开票金额', dataIndex: 'InvoiceAmount', align: 'right' },
    { title: '税额', dataIndex: 'InvoiceTaxAmount', align: 'right' },
    // { title: '操作', dataIndex: 'action', align: 'left', scopedSlots: { customRender: 'action' }, width: '10%' }
]

export default {
    components: {
        Token
    },
    mounted() {
        this.$nextTick(() => {
            // 页面渲染完成后的回调
            // this.tableHeight = this.getTableHeight(true) + 24
            this.time = [this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth(), 1)), this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))]
            this.getDataList()
        })
        // this.getDataList()
    },
    data() {
        return {
            headers: {
                authorization: 'Bearer ' + Token.getToken()
            },
            data: [],
            visible: false,
            timeDisabled: true,
            pagination: {
                current: 1,
                pageSize: 25,
                showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
                pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
                showSizeChanger: true
            },
            filters: {},
            sorter: { field: 'dDate', order: 'desc' },
            loading: false,
            columns,
            time: [],
            queryParam: { condition: 'salesman' },
            visibleUpload: false,
            selectedRowKeys: [],
            selectTime:0,
        }
    },
    methods: {
        openhtml() {
            this.$http.post('/OrderManagement/SO_SOMain/ExportSO_SOMainAndRuleToExcel', {}).then(resJson => {
                if (resJson.Success) {
                    download(resJson.Data.fileUrl, resJson.Data.fileName)
                    this.visible = false
                } else {
                    this.$message.error(resJson.Msg)
                }
            })
        },
        repossess() {
            this.queryParam = { condition: 'salesman' }
            this.changeTime(0);
            this.getDataList();
        },
        handleTableChange(pagination, filters, sorter) {
            this.pagination = { ...pagination }
            this.filters = { ...filters }

            this.getDataList()
        },
        onSelectChange(selectedRowKeys) {
            this.selectedRowKeys = selectedRowKeys
        },
        //导出
        downloadTemplate() {
            this.$http.post('/InvoiceManagement/v_salesmaninvoicestatistics/SalessmanExport', {
                Search: { ...this.queryParam, StartTime: this.time[0] ? this.timeFormat(this.time[0]) : "", EndTime: this.time[1] ? this.timeFormat(this.time[1]) : "" },
            }, { responseType: 'blob' }).then(res => {
                const url = URL.createObjectURL(res)
                const fileName = '业务员开票统计'
                const aTag = document.createElement('a')
                aTag.download = fileName
                aTag.href = url
                aTag.click()
                URL.revokeObjectURL(aTag.href)
            }).catch(err => {
                this.$message.error(err);
            })
        },
        getDataList() {
            this.selectedRowKeys = []

            this.loading = true
            this.$http
                .post('/InvoiceManagement/v_salesmaninvoicestatistics/GetDataList', {
                    PageIndex: this.pagination.current,
                    PageRows: this.pagination.pageSize,
                    SortField: 'Id',
                    SortType: 'desc',
                    // DeptId: this.DeptId,
                    Search: { ...this.queryParam, StartTime: this.time[0] ? this.timeFormat(this.time[0]) : "", EndTime: this.time[1] ? this.timeFormat(this.time[1]) : "" },
                    // ...this.filters
                })
                .then(resJson => {
                    this.loading = false
                    this.data = resJson.Data
                    this.data.forEach(item => {
                        item.InventoryAmount = this.$options.filters.NumberFormats(item.InventoryAmount)
                        item.InvoiceAmount = this.$options.filters.NumberFormats(item.InvoiceAmount)
                        item.InvoiceTaxAmount = this.$options.filters.NumberFormats(item.InvoiceTaxAmount)
                    })
                    if (this.data) {
                        const pagination = { ...this.pagination }
                        pagination.total = resJson.Total
                        this.pagination = pagination
                    }
                })
        },
        // 导入文件类型
        handleChange(info) {
            if (info.file.status !== 'uploading') {
            }
            if (info.file.status === 'done') {
                if (info.file.response.Success === false) {
                    this.$message.error(`${info.file.name}文件,${info.file.response.Msg},请检查文件内容！ `)
                } else {
                    this.$message.success(`${info.file.name}  文件上传成功！`)
                    this.getDataList()
                }
                this.visible = false
            } else if (info.file.status === 'error') {
                this.$message.error(`${info.file.name} 文件上传失败！`)
            }
        },
        hasSelected() {
            return this.selectedRowKeys.length > 0
        },
        //导入
        handleImport() {
            this.visibleUpload = true;
        },
        handleAdd() {
            this.$refs.editForm.openForm(null, '新建销售订单主表信息')
        },
        handleEdit(id) {
            this.$refs.editForm.openForm(id, '订单详情')
        },
        changeTime(e) {
            this.timeDisabled = true;
            this.selectTime = e;
            this.time = [];
            switch (e) {
                case 0:
                    this.time[0] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth(), 1))
                    this.time[1] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))
                    break
                case 1:
                    this.time[0] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() - 2, 1))
                    this.time[1] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))
                    break
                case 2:
                    this.time[0] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() - 5, 1))
                    this.time[1] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))
                    break
                case 3:
                    this.timeDisabled = false;
                    break
            }
        },
        handleDelete(ids) {
            var thisObj = this
            // this.$confirm({
            //   title: '确认删除吗?',
            //   onOk() {
            //     return new Promise((resolve, reject) => {
            //       thisObj.$http.post('/OrderManagement/SO_SOMain/DeleteData', ids).then(resJson => {
            //         resolve()

            //         if (resJson.Success) {
            //           thisObj.$message.success('操作成功!')

            //           thisObj.getDataList()
            //         } else {
            //           thisObj.$message.error(resJson.Msg)
            //         }
            //       })
            //     })
            //   }
            // })

            this.$confirm('确认删除吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                thisObj.$http
                    .post('/OrderManagement/SO_SOMain/DeleteData', ids)
                    .then(resJson => {
                        // resolve()

                        if (resJson.Success) {
                            thisObj.$message.success('操作成功!')

                            thisObj.getDataList()
                        } else {
                            thisObj.$message.error(resJson.Msg)
                        }
                    })
            })
        },
        timeFormat(val) {
            // 时间格式化函数
            return moment(val).format('YYYY-MM-DD')
        }
    }
}
</script>

<style scoped>
.flax {
    display: flex;
    justify-content: space-between;
}

/* .download {
  float: right;
  display: flex;
  align-items: center;
} */
/deep/ .ant-card-body {
    padding-bottom: 0px;
}
</style>